const form = document.getElementById('form') as HTMLFormElement
const username = document.getElementById('username') as HTMLInputElement
const email = document.getElementById('email') as HTMLInputElement
const password = document.getElementById('password') as HTMLInputElement
const password2 = document.getElementById('password2') as HTMLInputElement

// check email is valid、check rrequired fields、check input length、check password match
function checkEmail(input: HTMLInputElement) {
  const re: RegExp = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
  if (re.test(input.value.trim())) {
    showSuccess(input)
  } else {
    showError(input, '邮箱地址无效')
  }
}
function checkRequired(inputArr: Array<HTMLInputElement>) {
  inputArr.forEach((input) => {
    if (input.value.trim() === '') {
      showError(input, `${getFieldName(input)}是必填项`)
    } else {
      showSuccess(input)
    }
  })
}
function checkLength(input: HTMLInputElement, min: number, max: number) {
  if (input.value.trim().length < min) {
    showError(input, `${getFieldName(input)}必须大于${min}个字符`)
  } else if (input.value.trim().length > max) {
    showError(input, `${getFieldName(input)}不能大于${max}个字符`)
  } else {
    showSuccess(input)
  }
}
function checkPasswordsMatch(input1: HTMLInputElement, input2: HTMLInputElement) {
  if (input1.value.trim() !== input2.value.trim()) {
    showError(input2, '密码不匹配')
  }
}

// get 字段名、Show input error message、show success outline
function getFieldName(input: HTMLInputElement) {
  const formControl = input.parentElement
  const label = formControl.querySelector('label')
  return label.innerText
}
function showError(input: HTMLInputElement, message: string) {
  const formControl = input.parentElement
  formControl.className = 'form-control error'
  const small = formControl.querySelector('small')
  small.innerText = message
}
function showSuccess(input: HTMLInputElement) {
  const formControl = input.parentElement
  formControl.className = 'form-control success'
}

// event listener
document.addEventListener('submit', (e) => {
  e.preventDefault()

  checkRequired([username, email, password, password2])
  checkLength(username, 3, 15)
  checkLength(password, 6, 25)
  checkEmail(email)
  checkPasswordsMatch(password, password2)
})
